package com.haochang.chunkvod.controller.activity.hostess;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.database.order.BaseInfoDao;
import com.haochang.chunkvod.app.database.order.PartInfoDao;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.HelperUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.controller.activity.order.PartModifyActivity;
import com.haochang.chunkvod.controller.adapter.hostess.HostessHomePageAdapter;
import com.haochang.chunkvod.model.BaseInfo;
import com.haochang.chunkvod.model.hostess.HostessData;
import com.haochang.chunkvod.model.hostess.HostessInfo;
import com.haochang.chunkvod.model.order.PartInfo;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshBase;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshGridView;
import com.haochang.chunkvod.view.vod.partition.PartLayout;
import com.haochang.chunkvod.view.vod.popupWindow.SecondMenuInfo;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;

/**
 * created at 2016/8/23 10:27
 * 咨客首页
 */
public class HostessHomeActivity extends BaseActivity
{
	//控件
	private TitleView titleView;
	private BaseTextView tv_hostessNotice;//顶部提示
	private PullToRefreshGridView gridView;
	private PartLayout tabSwitcher;//底部HorizantalScollview
	private VodPopWindow pop;

	private int noticeCount = 0;//顶部提示数量
	private List<PartInfo> partInfoList = new ArrayList<PartInfo>();//底部分区list
	private String pId = "";//分区id

	private HostessHomePageAdapter adapter;//咨客首页 房间/桌台适配器
	private List<HostessInfo> roomInfoList = new ArrayList<HostessInfo>();//隐藏买单未离后的房间list
	private List<HostessInfo> allRoomInfoList = new ArrayList<HostessInfo>();//所有的房间list
	private HostessData hostessData;

	private boolean showUnLeave = true;//是否显示买单未离,默认显示
	private List<SecondMenuInfo> listSecondMenuRoom = new ArrayList<SecondMenuInfo>();//排序的二级menu 房间
	private List<SecondMenuInfo> listSecondMenuDesk = new ArrayList<SecondMenuInfo>();//排序的二级menu 桌台
	private String roomSortType = "0";//默认 房间按房号排序
	private String deskSortType = "0";//默认 桌台按**排序
	//排序类型  默认按房间排序

	private enum SortType
	{
		Room, Desk
	}

	private SortType hostessType = SortType.Room;//排序类型  默认按房间排序

	private Timer timer;//定时器
	private TimerTask timerTask;

	@Override
	public void receiveParam()
	{

	}

	@Override
	public void initData()
	{
		//获取缓存的显示选项,默认为room
		String hostessShowType = HelperUtils.getHelperAppInstance().getSValue("hostessShowType", "room");
		hostessType = TextUtils.equals("desk", hostessShowType) ? SortType.Desk : SortType.Room;
		showUnLeave = HelperUtils.getHelperAppInstance().getBValue("showUnLeave", true);
		hostessData = new HostessData(HostessHomeActivity.this);
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_hostess_home);
		View img_hostess_modify = findViewById(R.id.img_hostess_modify);//底部右侧添加分区
		titleView = (TitleView) findViewById(R.id.titleView);
		tv_hostessNotice = (BaseTextView) findViewById(R.id.tv_hostessNotice);
		titleView.setTitle(R.string.hostess).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				finish();
				animRightToLeft();
			}

			@Override
			public void onDoneClick()
			{
				List<String> list = new ArrayList<String>();
				list.add("可用房型");//0
				list.add("预留房间");//1
				list.add("现场排号");//2
				list.add("消费查询");//3
				list.add("发送字幕");//4
				list.add("预收/代付");//5
				list.add("预订信息");//6
				list.add("排序方式=sec");//7
				list.add("设置=sec");//8
				list.add("退出登录");//9
				int location[] = new int[2];
				ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
				img.getLocationOnScreen(location);
				int x = location[0];
				pop = new VodPopWindow(HostessHomeActivity.this, list);
				pop.showPopupWindow(titleView, x);
				pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
				{
					@Override
					public void onSelectItem(int position)
					{
						switch (position)
						{
						case 0:
							//可用房型
							startEnterActivity(OneKeyOpenRoomActivity.class);
							break;
						case 1:
							//跳转到预留房间
							startEnterActivity(ReserveActivity.class);
							break;
						case 11:// // TODO: 2016/10/31 待写
							//跳转到  可用房间
							startEnterActivity(UsableRoomActivity.class);
							break;
						case 2:
							//跳转到  现场排号
							startEnterActivity(LiveARowNumberActivity.class);
							break;
						case 3:
							//跳转到  消费查询
							startEnterActivity(ConsumeQueryActivity.class);
							break;
						case 4:
							//跳转到  发送字幕
							startEnterActivity(SendSubtitleActivity.class);
							break;
						case 5:
							//跳转到  预收/代付
							startEnterActivity(AdvancesReceivedAndInsteadChargingActivity.class);
							break;
						case 6:
							//跳转到  预订信息
							startEnterActivity(ReserveRoomActivity.class);
							break;
						case 7:
							if (hostessType == SortType.Room)
							{
								//弹出排序方式--房间
								if (listSecondMenuRoom != null && listSecondMenuRoom.size() > 0)
								{
									for (SecondMenuInfo info : listSecondMenuRoom)
									{
										info.setSelected(TextUtils.equals(roomSortType, info.getCode()));
									}
									pop.showSecondMenuView(4, listSecondMenuRoom, true);
									pop.setPopWindowLeftListListener(new VodPopWindow.OnPopWindowLeftListListener()
									{
										@Override
										public void onSelectItem(int position)
										{
											//保存选择的排序方式
											roomSortType = listSecondMenuRoom.get(position).getCode();
											deskSortType = "";//  清空 已选桌台
											requestRoomOrDeskList(pId, true);//按排序方式查询数据
										}
									});
								} else
								{
									ToastUtils.showText(HostessHomeActivity.this, "未获取房间排序方式");
								}
							} else
							{
								//弹出排序方式--桌台
								if (listSecondMenuDesk != null && listSecondMenuDesk.size() > 0)
								{
									for (SecondMenuInfo info : listSecondMenuDesk)
									{
										info.setSelected(TextUtils.equals(deskSortType, info.getCode()));
									}
									pop.showSecondMenuView(4, listSecondMenuRoom, true);
									pop.setPopWindowLeftListListener(new VodPopWindow.OnPopWindowLeftListListener()
									{
										@Override
										public void onSelectItem(int position)
										{
											//保存选择的排序方式
											deskSortType = listSecondMenuDesk.get(position).getCode();
											roomSortType = "";//  清空 已选房间
											requestRoomOrDeskList(pId, true);//按排序方式查询数据
										}
									});
								} else
								{
									ToastUtils.showText(HostessHomeActivity.this, "未获取桌台排序方式");
								}
							}
							break;
						case 8:
							//弹出设置
							List<SecondMenuInfo> list = new ArrayList<SecondMenuInfo>();
							list.add(new SecondMenuInfo("开房顺序", "0", false));
							//当前为显示桌台时 切换 至 显示房间 //当前为显示房间时 切换 至 显示桌台
							list.add(new SecondMenuInfo(hostessType == SortType.Desk ? "显示房间" : "显示桌台", "1", false));
							list.add(new SecondMenuInfo(showUnLeave ? "隐藏买单未离桌台" : "显示买单未离桌台", "2", false));
							pop.showSecondMenuView(5, list, false);
							pop.setPopWindowLeftListListener(new VodPopWindow.OnPopWindowLeftListListener()
							{
								@Override
								public void onSelectItem(int position)
								{
									switch (position)
									{
									case 0:
										//跳转到开房顺序设置界面
										startEnterActivity(SortRoomFirstActivity.class);
										break;
									case 1:
										//显示房间/桌台
										HelperUtils.getHelperAppInstance().setValue("hostessShowType", hostessType == SortType.Room ? "desk" : "room");
										hostessType = hostessType == SortType.Room ? SortType.Desk : SortType.Room;
										initBottomView();
										requestRoomOrDeskList(pId, true);//按排序方式查询数据
										break;
									case 2:
										HelperUtils.getHelperAppInstance().setValue("showUnLeave", !showUnLeave);
										showUnLeave = !showUnLeave;
										showByLeave();
										break;
									}
								}
							});
							break;
						case 9:
							loginOut();
							break;
						}
					}
				});
			}
		});

		gridView = (PullToRefreshGridView) findViewById(R.id.gird_hostessInfo);
		gridView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
		gridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>()
		{

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView)
			{
				//刷新数据
				requestRoomOrDeskList(pId, false);
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView)
			{

			}
		});
		tv_hostessNotice.setOnClickListener(mOnBaseClickListener);
		img_hostess_modify.setOnClickListener(mOnBaseClickListener);

		tabSwitcher = (PartLayout) findViewById(R.id.tabSwitcher);
		if (!CollectionUtils.isEmpty(partInfoList))
		{
			for (PartInfo info : partInfoList)
			{
				tabSwitcher.addTab(info);
			}
		}
		//显示列表
		adapter = new HostessHomePageAdapter(HostessHomeActivity.this, R.layout.item_home_page_order_grid_layout, roomInfoList);
		gridView.setAdapter(adapter);

		tabSwitcher.setOnTabChangedListener(new PartLayout.OnTabChangedListener()
		{
			@Override
			public void onTabChanged(int last, int current, String partId)
			{
				tabSwitcher.setSelectedTable(current, partId);
				pId = partId;
				requestRoomOrDeskList(partId, true);
			}
		});
		initBottomView();//初始化底部选择控件
		requestRoomOrDeskList(pId, true);//获取第一个即全部分区的包房信息
	}

	/**
	 * 处理底部选择
	 */
	private void initBottomView()
	{
		partInfoList.clear();
		List<PartInfo> list = PartInfoDao.getDao().queryBuilderAll(PartInfo.class, hostessType == SortType.Desk ? "is_table_select" : "is_room_select", true);
		if (!CollectionUtils.isEmpty(list))
		{
			StringBuilder sb = new StringBuilder();
			for (PartInfo partInfo : list)
			{
				sb.append(partInfo.getPart_id()).append(",");
			}
			PartInfo info = new PartInfo();
			info.setPartName("全部");
			info.setPart_id(pId = sb.toString());
			partInfoList.add(info);
			partInfoList.addAll(list);
		} else
		{
			PartInfo info = new PartInfo();
			info.setPartName("全部");
			info.setPart_id(pId = "");
			partInfoList.add(info);
		}
		tabSwitcher.removeAllViews();
		tabSwitcher.cleanTabView();
		if (!CollectionUtils.isEmpty(partInfoList))
		{
			for (PartInfo info : partInfoList)
			{
				tabSwitcher.addTab(info);
			}
		}
	}

	/**
	 * 根据是否显示买单未离显示数据
	 */
	@SuppressWarnings("unchecked")
	private void showByLeave()
	{
		if (showUnLeave)
		{
			adapter.replaceAll(allRoomInfoList);
		} else
		{
			roomInfoList.clear();
			if (hostessType == SortType.Room)
			{
				for (HostessInfo info : allRoomInfoList)
				{
					if (info.getUnLeave() != 1)
					{
						roomInfoList.add(info);
					}
				}
			} else
			{
				for (HostessInfo info : allRoomInfoList)
				{
					if (!TextUtils.isEmpty(info.getRoomStatus()) && !"paied".equals(info.getRoomStatus()))
					{
						roomInfoList.add(info);
					}
				}
			}
			adapter.replaceAll(roomInfoList);
		}
	}

	/**
	 * 获取房间或者桌台列表
	 *
	 * @param area_id 区域id
	 */
	public void requestRoomOrDeskList(final String area_id, final boolean isLoading)
	{
		final List<BaseInfo> baseInfoList = BaseInfoDao.getDao().queryBuilderAll(BaseInfo.class, "is_room", !(hostessType == SortType.Desk));//颜色信息
		adapter.setHasAnimation(false);
		hostessData.requestHomepageRoomOrDeskList(hostessType == SortType.Room, area_id, isLoading, roomSortType, new HostessData.IHostessHomeListener()
		{
			@Override
			public void onSuccess(int notifyCount, List<HostessInfo> list, List<SecondMenuInfo> listSecondMenu1)
			{
				if (adapter != null)
					adapter.clearAllAnimation();
				adapter.stopVibratorAndVoice();
				gridView.onRefreshComplete();
				adapter.setBaseInfoList(baseInfoList);
				if (!CollectionUtils.isEmpty(list))
				{
					roomInfoList.clear();
					allRoomInfoList.clear();
					roomInfoList.addAll(list);
					allRoomInfoList.addAll(list);
				} else
				{
					roomInfoList.clear();
					allRoomInfoList.clear();
					ToastUtils.showText(context, hostessType == SortType.Room ? "此分区暂时没有房间" : "此分区暂时没有桌台");
				}
				showByLeave();
				//排序列表
				if (listSecondMenu1 != null)
					listSecondMenuRoom = listSecondMenu1;
				// TODO: 2016/10/20 返回桌台二级menu
				//                    listSecondMenuDesk = listSecondMenu1;//这里需要返回一个桌台的排序方法
				if (hostessType == SortType.Room)
				{
					//获取提醒数量
					noticeCount = notifyCount;
					if (noticeCount > 0)
					{
						tv_hostessNotice.setVisibility(View.VISIBLE);
						tv_hostessNotice.setText(String.format(Locale.CHINA, "您有%d条提醒", noticeCount));
					} else
						tv_hostessNotice.setVisibility(View.GONE);
				} else
					tv_hostessNotice.setVisibility(View.GONE);
			}

			@Override
			public void onFail(int errno, String errMsg)
			{
				gridView.onRefreshComplete();
				if (errno != 5000 && !TextUtils.isEmpty(errMsg))
					ToastUtils.showText(HostessHomeActivity.this, errMsg);
			}
		});
	}

	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.img_hostess_modify:
				Intent intent = new Intent(HostessHomeActivity.this, PartModifyActivity.class);
				intent.putExtra(IntentKey.ROOM_TABLE_TYPE,
						hostessType == SortType.Desk ? PartModifyActivity.RoomTypeEnum.TABLE : PartModifyActivity.RoomTypeEnum.ROOM);
				startActivityForResult(intent, IntentCode.PART_DATA_REQUEST);
				break;
			case R.id.tv_hostessNotice:
				startEnterActivity(RemindActivity.class);
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == IntentCode.PART_DATA_REQUEST && resultCode == RESULT_OK && data != null)
		{
			ArrayList<PartInfo> selectPartList = data.getParcelableArrayListExtra(IntentKey.PART_DATA);
			tabSwitcher.removeAllViews();
			tabSwitcher.cleanTabView();
			tabSwitcher.setVisibility(View.VISIBLE);
			PartInfo info = new PartInfo();
			info.setPartName("全部");
			if (CollectionUtils.isEmpty(selectPartList))
			{
				info.setPart_id("");
				tabSwitcher.addTab(info);
			} else
			{
				StringBuilder sb = new StringBuilder();
				for (PartInfo partInfo : selectPartList)
				{
					sb.append(partInfo.getPart_id()).append(",");
				}
				info.setPart_id(sb.toString());
				tabSwitcher.addTab(info);
				for (PartInfo partInfo : selectPartList)
				{
					tabSwitcher.addTab(partInfo);
				}
			}
			tabSwitcher.setSelectedTable(0, info.getPart_id());
			pId = info.getPart_id();
			requestRoomOrDeskList(info.getPart_id(), true);
		} else if (requestCode == IntentCode.HOSTESS_MANAGER)
		{
			if (RESULT_OK == resultCode && data != null)
			{
				String roomId = data.getStringExtra(IntentKey.ROOM_ID);
				String remarks = data.getStringExtra(IntentKey.REMARKS);
				String state = data.getStringExtra(IntentKey.ROOM_STATUS);
				for (HostessInfo info : allRoomInfoList)
				{//本地先刷新adapter
					if (TextUtils.equals(info.getRoomId(), roomId))
					{
						if (!TextUtils.isEmpty(remarks))
						{
							info.setRemarks(remarks);
						}
						int count = 0;
						try
						{
							count = Integer.parseInt(data.getStringExtra(IntentKey.COMSTMER_COUNT));
						} catch (Exception e)
						{
							e.printStackTrace();
						}
						info.setCustomerCount(count);
						if (!TextUtils.isEmpty(state))
							info.setRoomStatus(state);
						adapter.notifyDataSetChanged();
						return;
					}
				}
			}
			requestRoomOrDeskList(pId, true);
		}
	}

	@Override
	public void onPause()
	{
		super.onPause();
		cancelTimerTask();
		if (null != adapter)
			adapter.stopVibratorAndVoice();
	}

	@Override
	public void onResume()
	{
		super.onResume();
		startTimerTask();
		if (null != adapter)
			adapter.startVibratorAndVoice();
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		cancelTimerTask();
		if (null != adapter)
			adapter.stopVibratorAndVoice();
	}

	private void startTimerTask()
	{
		if (timer == null)
		{
			timer = new Timer();
			timerTask = new TimerTask()
			{
				@Override
				public void run()
				{
					requestRoomOrDeskList(pId, false);
				}
			};
		}
		timer.schedule(timerTask, 30000, 30000);
	}

	/**
	 * 取消定时任务
	 */
	private void cancelTimerTask()
	{
		if (null != timerTask)
		{
			timerTask.cancel();
			timerTask = null;
		}
		if (null != timer)
		{
			timer.cancel();
			timer = null;
		}
	}
}
